<template>
  <div class="user-management">
    <div class="page-header">
      <h1>用户管理</h1>
      <p>管理系统中的所有普通用户信息</p>
    </div>

    <div class="content-card">
      <div class="toolbar">
        <button class="btn btn-primary" @click="showAddModal">新增用户</button>
        <div class="search-box">
          <input 
            type="text" 
            v-model="searchKeyword" 
            placeholder="搜索用户名、姓名或邮箱..."
            @input="filterUsers"
          >
        </div>
      </div>
      
      <div class="table-container">
        <table class="user-table">
          <thead>
            <tr>
              <th>用户ID</th>
              <th>头像</th>
              <th>用户名</th>
              <th>姓名</th>
              <th>手机号</th>
              <th>邮箱</th>
              <th>性别</th>
              <th>年龄</th>
              <th>注册时间</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in filteredUsers" :key="user.userId">
              <td>{{ user.userId }}</td>
              <td>
                <img 
                  :src="user.avatar || require('@/assets/product-default.png')" 
                  :alt="user.username"
                  class="avatar-img"
                  @error="handleImageError"
                >
              </td>
              <td>{{ user.username }}</td>
              <td>{{ user.realName || '-' }}</td>
              <td>{{ user.phone || '-' }}</td>
              <td>{{ user.email || '-' }}</td>
              <td>{{ user.gender === 1 ? '男' : user.gender === 2 ? '女' : '-' }}</td>
              <td>{{ user.age || '-' }}</td>
              <td>{{ formatDate(user.createTime) }}</td>
              <td>
                <span :class="['status', user.status === 1 ? 'active' : 'inactive']">
                  {{ user.status === 1 ? '正常' : '禁用' }}
                </span>
              </td>
              <td>
                <button class="btn btn-edit" @click="editUser(user)">修改</button>
                <button 
                  :class="['btn', user.status === 1 ? 'btn-disable' : 'btn-enable']"
                  @click="toggleUserStatus(user)"
                >
                  {{ user.status === 1 ? '禁用' : '启用' }}
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 新增/编辑用户模态框 -->
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ isEditing ? '修改用户信息' : '新增用户' }}</h3>
          <button class="close-btn" @click="closeModal">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveUser">
            <div class="form-row">
              <div class="form-group">
                <label>用户名 *</label>
                <input type="text" v-model="editingUser.username" required>
              </div>
              <div class="form-group">
                <label>姓名</label>
                <input type="text" v-model="editingUser.realName">
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>手机号</label>
                <input type="tel" v-model="editingUser.phone">
              </div>
              <div class="form-group">
                <label>邮箱</label>
                <input type="email" v-model="editingUser.email">
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>性别</label>
                <select v-model="editingUser.gender">
                  <option value="">请选择</option>
                  <option value="1">男</option>
                  <option value="2">女</option>
                </select>
              </div>
              <div class="form-group">
                <label>年龄</label>
                <input type="number" v-model="editingUser.age" min="1" max="120">
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>密码 {{ isEditing ? '(留空则不修改)' : '*' }}</label>
                <input type="password" v-model="editingUser.password" :required="!isEditing">
              </div>
              <div class="form-group">
                <label>状态</label>
                <select v-model="editingUser.status">
                  <option value="1">正常</option>
                  <option value="0">禁用</option>
                </select>
              </div>
            </div>
            <div class="form-actions">
              <button type="button" class="btn btn-secondary" @click="closeModal">取消</button>
              <button type="submit" class="btn btn-primary">{{ isEditing ? '保存' : '新增' }}</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getAllUsers, addUser, updateUser, deleteUser, hardDeleteUser, updateUserStatus } from '@/api/admin';

export default {
  name: 'UserManagement',
  data() {
    return {
      users: [],
      filteredUsers: [],
      searchKeyword: '',
      showModal: false,
      isEditing: false,
      editingUser: {
        username: '',
        realName: '',
        phone: '',
        email: '',
        gender: '',
        age: '',
        password: '',
        status: 1,
        isAdmin: 0
      },
      loading: false
    }
  },
  mounted() {
    this.fetchUsers();
  },
  methods: {
    async fetchUsers() {
      try {
        this.loading = true;
        console.log('开始获取用户数据...');
        const response = await getAllUsers();
        console.log('用户API响应:', response);
        
        // 检查响应是否为数组
        if (Array.isArray(response)) {
          this.users = response.filter(user => user.isAdmin === 0);
          this.filteredUsers = [...this.users];
          console.log('用户数据:', this.users);
        } else {
          console.error('API返回的不是数组:', response);
          this.users = [];
          this.filteredUsers = [];
          alert('获取用户数据格式错误');
        }
      } catch (error) {
        console.error('获取用户列表失败:', error);
        console.error('错误详情:', error.response || error);
        this.users = [];
        this.filteredUsers = [];
        alert('获取用户列表失败: ' + error.message);
      } finally {
        this.loading = false;
      }
    },
    filterUsers() {
      if (!this.searchKeyword.trim()) {
        this.filteredUsers = [...this.users];
        return;
      }
      
      const keyword = this.searchKeyword.toLowerCase();
      this.filteredUsers = this.users.filter(user => 
        user.username.toLowerCase().includes(keyword) ||
        (user.realName && user.realName.toLowerCase().includes(keyword)) ||
        (user.email && user.email.toLowerCase().includes(keyword))
      );
    },
    handleImageError(event) {
      event.target.src = require('@/assets/product-default.png');
    },
    formatDate(dateString) {
      if (!dateString) return '-';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN');
    },
    showAddModal() {
      this.isEditing = false;
      this.editingUser = {
        username: '',
        realName: '',
        phone: '',
        email: '',
        gender: '',
        age: '',
        password: '',
        status: 1,
        isAdmin: 0
      };
      this.showModal = true;
    },
    editUser(user) {
      this.isEditing = true;
      this.editingUser = { ...user };
      this.showModal = true;
    },
    async saveUser() {
      try {
        let response;
        if (this.isEditing) {
          // 编辑用户
          response = await updateUser(this.editingUser);
        } else {
          // 新增用户
          response = await addUser(this.editingUser);
        }
        
        if (response.status === 200 || response.msg.includes('成功')) {
          alert(this.isEditing ? '用户信息修改成功' : '用户新增成功');
          this.closeModal();
          this.fetchUsers();
        } else {
          alert(this.isEditing ? '修改失败' : '新增失败');
        }
      } catch (error) {
        console.error(this.isEditing ? '修改用户信息失败:' : '新增用户失败:', error);
        alert(this.isEditing ? '修改用户信息失败' : '新增用户失败');
      }
    },
    async toggleUserStatus(user) {
      const newStatus = user.status === 1 ? 0 : 1;
      const action = newStatus === 1 ? '启用' : '禁用';
      
      if (!confirm(`确定要${action}用户 "${user.username}" 吗？`)) {
        return;
      }
      
      try {
        const response = await updateUserStatus(user.userId, newStatus);
        if (response.status === 200 || response.msg.includes('成功')) {
          alert(`用户${action}成功`);
          this.fetchUsers();
        } else {
          alert(`${action}失败`);
        }
      } catch (error) {
        console.error(`${action}用户失败:`, error);
        alert(`${action}用户失败`);
      }
    },
    async deleteUser(user) {
      const action = confirm(`警告：此操作将永久删除用户 "${user.username}"，无法恢复！\n\n确定要继续吗？`);
      
      try {
        let response;
        if (action) {
          // 永久删除用户
          response = await hardDeleteUser(user.userId);
          if (response.status === 200 || response.msg.includes('成功')) {
            alert('用户已永久删除');
            this.fetchUsers();
          } else {
            alert('删除失败');
          }
        }
      } catch (error) {
        console.error('操作失败:', error);
        alert('操作失败');
      }
    },
    closeModal() {
      this.showModal = false;
      this.editingUser = {
        username: '',
        realName: '',
        phone: '',
        email: '',
        gender: '',
        age: '',
        password: '',
        status: 1,
        isAdmin: 0
      };
    }
  }
}
</script>

<style scoped>
.user-management {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0 0 10px 0;
  color: #2c3e50;
  font-size: 2rem;
}

.page-header p {
  margin: 0;
  color: #7f8c8d;
}

.content-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  overflow: hidden;
}

.toolbar {
  padding: 20px;
  border-bottom: 1px solid #ecf0f1;
}

.search-box {
  position: relative;
}

.search-box input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 0.875rem;
}

.search-box input:focus {
  outline: none;
  border-color: #3498db;
}

.table-container {
  overflow-x: auto;
}

.user-table {
  width: 100%;
  border-collapse: collapse;
}

.user-table th,
.user-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ecf0f1;
}

.user-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #2c3e50;
}

.user-table tr:hover {
  background-color: #f8f9fa;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875rem;
}

.status.active {
  background-color: #d4edda;
  color: #155724;
}

.status.inactive {
  background-color: #f8d7da;
  color: #721c24;
}

.btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.875rem;
  margin-right: 5px;
  transition: all 0.3s ease;
}

.btn-edit {
  background-color: #3498db;
  color: white;
}

.btn-edit:hover {
  background-color: #2980b9;
}

.btn-delete {
  background-color: #e74c3c;
  color: white;
}

.btn-delete:hover {
  background-color: #c0392b;
}

.btn-primary {
  background-color: #3498db;
  color: white;
}

.btn-primary:hover {
  background-color: #2980b9;
}

.btn-enable {
  background-color: #27ae60;
  color: white;
}

.btn-enable:hover {
  background-color: #229954;
}

.btn-disable {
  background-color: #e67e22;
  color: white;
}

.btn-disable:hover {
  background-color: #d35400;
}

.btn-secondary {
  background-color: #95a5a6;
  color: white;
}

.avatar-img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ecf0f1;
}

.modal-header h3 {
  margin: 0;
  color: #2c3e50;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #7f8c8d;
}

.modal-body {
  padding: 20px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #2c3e50;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 0.875rem;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #3498db;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}
</style>